package net.dgg.dggcloud.service.jrcrm.common.webscoket.message.impl;

import com.google.gson.Gson;
import net.dgg.dggcloud.service.jrcrm.common.webscoket.SystemWebSocketHandler;
import net.dgg.dggcloud.service.jrcrm.common.webscoket.message.MessageDelegateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Map;

/**
 * 接收消息的Listener,用于接收订阅到的消息.
 *
 * @author tanchaowen
 */
public class MessageDelegateListenerImpl implements MessageDelegateListener {

    private static Logger logger = LoggerFactory.getLogger(MessageDelegateListenerImpl.class);

    @Resource
    private SystemWebSocketHandler systemWebSocketHandler;

    private static Gson gson = new Gson();

    @Override
    public void handleMessage(Serializable message) {
        if (message instanceof Map<?, ?>) {
            Map msg = (Map) message;
            long receiverId = (long) msg.get("receiver");
            logger.info("消息发给  "+receiverId + "     " + message.toString());
            if (receiverId == 0) {
                //消息发给全部
                TextMessage textMessage = new TextMessage(gson.toJson(msg));
                systemWebSocketHandler.sendMessageToUsers(textMessage);
            } else {
                //发给个人
                TextMessage textMessage = new TextMessage(gson.toJson(msg));
                systemWebSocketHandler.sendMessageToUser(receiverId, textMessage);
            }

        }
    }
}